package cc.rengu.redp.bizimpl.upmp.controller;

import cc.rengu.igas.bomp.facade.BompMchntQueryService;
import cc.rengu.igas.bomp.facade.request.MchntAreaListQueryRequest;
import cc.rengu.igas.bomp.facade.request.MchntInfoListQueryRequest;
import cc.rengu.igas.momp.facade.bean.*;
import cc.rengu.igas.momp.facade.request.EditMchntFeeTxnAmtLimitRequest;
import cc.rengu.igas.momp.facade.request.QueryMchntFeeDiscountLimitRequest;
import cc.rengu.igas.momp.facade.request.QueryMchntFeeDiscountMcListInfoRequest;
import cc.rengu.igas.momp.facade.request.QueryMchntFeeTxnAmtLimitRequest;
import cc.rengu.igas.momp.facade.response.QueryMchntFeeDiscountLimitResponse;
import cc.rengu.igas.momp.facade.result.Result;
import cc.rengu.redp.bizimpl.constant.UpmpConstant;
import cc.rengu.redp.bizimpl.upmp.bean.CommissionAddMchntRequest;
import cc.rengu.redp.bizimpl.upmp.bean.CommissionInfo;
import cc.rengu.redp.bizimpl.upmp.bean.MarketManagerRequest;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpBMchntBaseInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpOrganization;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpSysParam;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpUserInfo;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.McMchntInfoVO;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.ExcelDownload;
import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.properties.RedpProperties;
import cc.rengu.redp.common.utils.SortUtil;
import cc.rengu.redp.common.utils.SpringContextUtil;
import cc.rengu.redp.system.domain.Organization;
import cc.rengu.redp.system.domain.OrganizationVO;
import cc.rengu.redp.system.domain.User;
import cc.rengu.redp.system.service.OrganizationService;
import cc.rengu.redp.system.service.UserService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import oracle.jdbc.proxy.annotation.Post;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "营销管理:银行对商户手续费优惠管理")
@Slf4j
@RestController
@RequestMapping("/admin/market/commissionManager")
public class CommissionMarketManagerController extends BaseController {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Autowired
    private IUpmpSysSeqService upmpSysSeqService;

    @Autowired
    private IUpmpUserInfoService userService;

    @Autowired
    private IUpmpOrganizationService iUpmpOrganizationService;

//    dubbo服务
    @Autowired
    private CommissionMarketService marketService;

    @Autowired
    private ICustomerMarketService customerMarketService;

//    @DubboReference(version = "2.2.0", url = "dubbo://172.17.100.9:62132", check = false)
    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompMchntQueryService bompMchntQueryService;

    @Log("分页")
    @GetMapping("/list")
    public IPage<MchntFeeDiscountMcListInfoBean> findByPage(QueryRequest request,QueryMchntFeeDiscountMcListInfoRequest req) throws RedpException {
        req.setQueryType("0");
        req.setQueryRole("00");
        IPage<MchntFeeDiscountMcListInfoBean> page=marketService.findByPage(request,req);
        if(page!=null && page.getSize()>0){
            List<MchntFeeDiscountMcListInfoBean> list=page.getRecords();
            for(MchntFeeDiscountMcListInfoBean bean:list){
                String userId=bean.getOprId();
                UpmpUserInfo user = userService.findById(userId);
                if(Common.isNotBlank(user)){
                    bean.setOprId(user.getUserName());
                }
            }
        }
        return page;
    }

    @Log("银行对商户手续费优惠管理:新增")
    @GetMapping("/add")
    public Map<String, Object> addShow() {
        Map<String, Object> map=new HashMap<>();
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpSysParam dataDict = upmpSysParamService.findByPrimaryKey("marketOrgSelectedFlag",user.getInstId(),null);

        map.put("instId", user.getInstId());
        if(Common.isNotBlank(dataDict)){
            map.put("marketOrgSelectedFlag",dataDict.getPrimaryValue());
        }
         dataDict = upmpSysParamService.findByPrimaryKey("supportTypeFlag",user.getInstId(),null);
        if(Common.isNotBlank(dataDict)){
            map.put("supportTypeFlag",dataDict.getPrimaryValue());
        }
        dataDict = upmpSysParamService.findByPrimaryKey("discountCeilingFlag",user.getInstId(),null);
        if(Common.isNotBlank(dataDict)){
            map.put("discountCeilingFlag",dataDict.getPrimaryValue());
        }
        dataDict = upmpSysParamService.findByPrimaryKey("mchntdesFlag",user.getInstId(),null);
        if(Common.isNotBlank(dataDict)){
            map.put("mchntdesFlag",dataDict.getPrimaryValue());
        }
        dataDict = upmpSysParamService.findByPrimaryKey("discountRule",user.getInstId(),null);
        if(Common.isNotBlank(dataDict)){
            map.put("discountRule",dataDict.getPrimaryValue());
        }
        return map;
    }
//
    @Log("银行对商户手续费优惠管理:修改")
    @GetMapping("/edit")
    public Map<String, Object> editShow(HttpServletRequest request) throws RedpException {
//        Map<String, Object> map=new HashMap<>();
//        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
//        map.put("instId", user.getInstId());
//        UpmpSysParam dict = upmpSysParamService.findByPrimaryKey("marketOrgSelectedFlag",user.getInstId(),null);
//
//        if(Common.isNotBlank(dict)){
//            map.put("marketOrgSelectedFlag",dict.getPrimaryValue());
//        }
//        dict = upmpSysParamService.findByPrimaryKey("supportTypeFlag",user.getInstId(),null);
//        if(Common.isNotBlank(dict)){
//            map.put("supportTypeFlag",dict.getPrimaryValue());
//        }
//        dict = upmpSysParamService.findByPrimaryKey("discountCeilingFlag",user.getInstId(),null);
//        if(Common.isNotBlank(dict)){
//            map.put("discountCeilingFlag",dict.getPrimaryValue());
//        }
//        dict = upmpSysParamService.findByPrimaryKey("mchntdesFlag",user.getInstId(),null);
//        if(Common.isNotBlank(dict)){
//            map.put("mchntdesFlag",dict.getPrimaryValue());
//        }
//        dict = upmpSysParamService.findByPrimaryKey("discountRule",user.getInstId(),null);
//        if(Common.isNotBlank(dict)){
//            map.put("discountRule",dict.getPrimaryValue());
//        }
//        String mcNo = request.getParameter("mcNo");
//        Map<String, Object> model = marketService.setModel(mcNo, "0", "00");
//        map.putAll(model);
//        List<McMchntInfoBean> circleList = customerMarketService.getMchntCircleList(mcNo, "-1", "-1");
//        map.put("circleList", circleList);
//        map.put("mcNo", mcNo);

        Map<String, Object> map=new HashMap<>();
        String mcNo = request.getParameter("mcNo");
        Map<String, Object> model = marketService.setModel(mcNo, "0", "00");
        map.putAll(model);
        return map;
    }

    @Log("查询机构")
    @PostMapping("/getOrgInfoList")
    public OperationResult getOrgInfoList(HttpServletRequest request) {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String orgName = request.getParameter("orgName");
        //TODO 参考老平台重新实现
        List<UpmpOrganization> orgListByParentCode = iUpmpOrganizationService.getOrgListByParentCode(orgName, user.getInstId());
        return OperationResult.buildSuccessResult("查询机构信息成功", orgListByParentCode);
    }
    /**
     *保存草稿，提交审批，修改草稿
     */
    @Log("银行对商户手续费优惠管理:新增,银行对商户手续费优惠管理:修改")
    @PostMapping("/add")
    public OperationResult addSave(@RequestBody CommissionInfo entity) throws RedpException {
        //判断操作类型
        String msg = "保存草稿成功！";
        if ("1".equals(entity.getOprType())) {
            msg = "提交成功，等待审核员通过后由发布员发布！";
        }
        entity.setQueryType("0");
        entity.setQueryRole("00");
        List<String> onLineProduce = entity.getOnLineProduce();
        List<String> upLineProduce = entity.getUpLineProduce();
        for(int i=0;i<onLineProduce.size();i++){
            String onProd= (String) onLineProduce.get(i);
            if("PM003000".equals(onProd) ||"PM003010".equals(onProd) ||"PM003020".equals(onProd) ||"PM003030".equals(onProd)){
                for(int j=0;j<upLineProduce.size();j++){
                    String upProd=(String)upLineProduce.get(j);
                    if(upProd.equals(onProd)){
                        upLineProduce.remove(upLineProduce.get(j));
                        break;
                    }
                }
            }
        }
        entity.setOnLineProduce(onLineProduce);
        entity.setUpLineProduce(upLineProduce);
        marketService.editSave(entity);
        return OperationResult.buildSuccessResult(msg);
    }

    public List<String> arrToList(String[] arr){
        ArrayList<String> result=new ArrayList<String>();
        if(arr != null){
            for(int i=0;i<arr.length;i++){
                result.add(arr[i]);
            }
        }
        return result;
    }
    public String[] ListToArr(List<String> list){
        String[] result=new String[list.size()];
        for(int i=0;i<list.size();i++){
            result[i]=list.get(i);
        }
        return result;
    }


    @Log(" 查询商户或者商圈的名称")
    @PostMapping("/getMerchanList")
    public OperationResult getMerchanList(@RequestBody McMchntInfoVO entity)  {
        // 可成功添加的列表
        List<McMchntInfoBean> mchntInfoList = new ArrayList<>();
        // 存在错误的列表
        List<McMchntInfoBean> errorList = new ArrayList<>();
        // 特殊费率商户的列表
        List<McMchntInfoBean> feeMchntList = new ArrayList<>();
        // 机构不符的列表
        List<McMchntInfoBean> orgMchntList = new ArrayList<>();

        // 页面选中的机构列表
        String orgInfoJson = StringEscapeUtils.unescapeHtml4(entity.getSelectedOrgInfoList());
        if (StringUtils.isBlank(orgInfoJson)) {
            return OperationResult.buildFailureResult("已选择的机构上送有误，请联系管理员");
        }
        List<McOrgInfoBean> orgInfoList = JSONArray.parseArray(orgInfoJson, McOrgInfoBean.class);
        Map<String, Boolean> selectedOrgMap = new HashMap<>();
        for (McOrgInfoBean mcOrgInfoBean : orgInfoList) {
            selectedOrgMap.put(mcOrgInfoBean.getOrgId(), true);
        }
        String msg = "商户";
        if ("0".equals(entity.getMchntType())) {
            msg = "商户";
        } else {
            msg = "商圈";
        }
        try {
            if (StringUtils.isBlank(entity.getMchntNo())) {
                return OperationResult.buildFailureResult("请输入有效的" + msg + "号");
            }
            String[] merchantArr = entity.getMchntNo().split(",");
            List<String> strings = Arrays.asList(merchantArr);
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

            if ("0".equals(entity.getMchntType())) {
                //商户
                MchntInfoListQueryRequest param = new MchntInfoListQueryRequest();
                strings.forEach((e) -> {
                    param.setMchntNo(e);
                    Map<String, Object> maps = null;
                    maps = marketService.queryMcNoList(user, param, genMerOrder(user));
                    if (null != maps.get("results")) {
                        List resultList = (List) maps.get("results");
                        Map mcMap = (Map) resultList.get(0);
                        McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                        mchntInfo1.setMchntNo((String) mcMap.get("id"));
                        mchntInfo1.setMchntName((String) mcMap.get("name"));
                        mchntInfo1.setMchntType("0");//----0-商户 1-商圈

                        Boolean isFeeMchntFlag = null;
                        isFeeMchntFlag = marketService.checkFeeMchnt(user, e, bompMchntQueryService, genMerOrder(user));
                        String orgId = (String) mcMap.get("orgId");
                        if (!selectedOrgMap.containsKey(orgId)) {
                            // 判断商户的机构与选择的机构是否一致
                            orgMchntList.add(mchntInfo1);
                        } else if (isFeeMchntFlag) {
                            // 判断商户是否特殊费率
                            feeMchntList.add(mchntInfo1);
                        } else {
                            // 可成功添加
                            mchntInfoList.add(mchntInfo1);
                        }
                    } else {
                        McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                        mchntInfo1.setMchntNo(e);
                        mchntInfo1.setMchntType("0");//----0-商户 1-商圈
                        errorList.add(mchntInfo1);
                    }
                });
            } else {
                //商圈
                MchntAreaListQueryRequest param = new MchntAreaListQueryRequest();
                MchntInfoListQueryRequest mchntInfoParam = new MchntInfoListQueryRequest();
                strings.forEach((e) -> {
                    param.setMchntArea(e);
                    Map<String, Object> maps = null;
                    maps = marketService.queryMchntAreaList(user, param, bompMchntQueryService, genMerOrder(user));
                    if (null != maps.get("results")) {
                        List resultList = (List) maps.get("results");
                        Map mcMap = (Map) resultList.get(0);
                        McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                        mchntInfo1.setMchntNo((String) mcMap.get("id"));
                        mchntInfo1.setMchntName((String) mcMap.get("name"));
                        mchntInfo1.setMchntType("1");//----0-商户 1-商圈

                        String orgId = (String) mcMap.get("orgId");
                        if (!selectedOrgMap.containsKey(orgId)) {
                            // 判断商户的机构与选择的机构是否一致
                            orgMchntList.add(mchntInfo1);
                        } else {
                            // 根据商圈编号查询商户列表
                            Set<String> stringSet = new HashSet<>();
                            mchntInfoParam.setMchntArea(e);
                            Map<String, Object> mchntMaps = null;
                            mchntMaps = marketService.queryMcNoList(user, mchntInfoParam, genMerOrder(user));
                            if (null != mchntMaps.get("results")) {
                                List mchntList = (List) mchntMaps.get("results");
                                for (Object obj : mchntList) {
                                    Map mchntMap = (Map) obj;
                                    String mchntNo = (String) mchntMap.get("id");
                                    // 判断商户是否特殊费率
                                    Boolean isFeeMchntFlag = null;
                                    isFeeMchntFlag = marketService.checkFeeMchnt(user, mchntNo, bompMchntQueryService, genMerOrder(user));
                                    if (isFeeMchntFlag) {
                                        if (!stringSet.contains(e)) {
                                            feeMchntList.add(mchntInfo1);
                                        }
                                    } else {
                                        // 可成功添加
                                        if (!stringSet.contains(e)) {
                                            mchntInfoList.add(mchntInfo1);
                                        }
                                    }
                                    stringSet.add(e);
                                }
                            } else {
                                // 可成功添加
                                mchntInfoList.add(mchntInfo1);
                            }
                        }
                    } else {
                        McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                        mchntInfo1.setMchntNo(e);
                        mchntInfo1.setMchntType("1");//----0-商户 1-商圈
                        errorList.add(mchntInfo1);
                    }
                });
            }
        } catch (Exception e) {
            log.error("获取" + msg + "信息时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("获取" + msg + "信息时系统异常");
        }
        Map<String, List<McMchntInfoBean>> resultMap = new HashMap<>();
        resultMap.put("successData", mchntInfoList);
        resultMap.put("errorData", errorList);
        resultMap.put("feeMchntData", feeMchntList);
        resultMap.put("orgMchntData", orgMchntList);
        return OperationResult.buildSuccessResult("查询成功", resultMap);
    }

    /**
     * 生成商户订单号（格式：MO + 8位日期 + 8位顺序号）
     */
    private String genMerOrder(UpmpUserInfoVO user) {
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService,user.getInstId());
        // 代理商编码前缀：MO（merOrder简写）
        String prefix = user.getInstId() + "MCMP";
        // 自动生成一级代码
        String paramCode = BusinessContainer.COMM_PARAM_CODE;
        // 生成序列号
        String seqNum = upmpSysSeqService.updateParamValue(paramCode, "MER_ORDER", channelId);
        // 8位日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date8 = sdf.format(new Date());
        // 商户订单号
        String merOrder = prefix + date8 + String.format("%08d", Integer.parseInt(seqNum));
        return merOrder;
    }

    @Log("下载模板")
    @PostMapping("/downloadExcel")
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String file = "mchntNoBatchImportTemplate.xls";
        ExcelDownload.getExcel(request, response, file);
    }


    private final static String commissionMarketMchntPath = SpringContextUtil.getBean(RedpProperties.class).getBaseFilePath();
    private static final String point = ".";

    @Log("银行对商户手续费优惠管理-导入")
    @PostMapping("/upload")
    public OperationResult getDataFromExcel(@RequestParam(value = "excelFile", required = false) MultipartFile excelFile, HttpServletRequest request) throws RedpException {
        if (excelFile == null) {
            log.error("请选择文件");
            return OperationResult.buildFailureResult("请选择文件");
        }
        String originalFilename = excelFile.getOriginalFilename();
        if (!originalFilename.endsWith(".xls") && !originalFilename.endsWith(".xlsx")) {
            log.error("文件不是excel类型");
            return OperationResult.buildFailureResult("文件不是excel类型");
        }
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String date = DateUtils.formatDate(new Date(), DateUtils.FORMAT_YYYYMMDD);
        File filePath = new File(commissionMarketMchntPath + user.getInstId() + File.separator +  date  );
        if (!filePath.exists()){
            filePath.mkdirs();
        }
        String suff = originalFilename.substring(originalFilename.lastIndexOf(point));
        String fileName = DateUtils.formatDate(new Date(), DateUtils.FULL_SEQ_FORMAT) + suff;
        String fileRealPath = filePath + File.separator + fileName;
        try (
                InputStream in = excelFile.getInputStream();
                OutputStream out = new FileOutputStream(filePath + File.separator + fileName)
        ) {
            IOUtils.copy(in, out);
        }catch (Exception e) {
            log.error("上传文件 " + originalFilename + " 时系统异常:[{}]", e);
            return OperationResult.buildFailureResult("文件上传失败");
        }

        return OperationResult.buildSuccessResult(fileRealPath);
    }

    @Log("删除营销活动")
    @PostMapping("/delete")
    public OperationResult deleteSubmit(HttpServletRequest request) throws RedpException {
        MarketManagerRequest entity=new MarketManagerRequest();
        entity.setMcNo(request.getParameter("mcNo"));
        if (StringUtils.isBlank(entity.getMcNo())) {
            throw new RedpException("营销活动编号不能为空");
        }
        entity.setOprType("0");
        entity.setMsg("商户手续费营销活动删除");
        entity.setQueryType("0");
        entity.setQueryRole("00");
        marketService.manageMchntFeeDiscountMc(entity);
        return OperationResult.buildSuccessResult("商户手续费营销活动删除成功");
    }

    @Log("增加商户")
    @GetMapping("/addMerchant")
    public Map<String, Object> addMerchantShow(HttpServletRequest request) throws RedpException {
        String mcNo = request.getParameter("mcNo");
        return marketService.setModel( mcNo, "0", "00");
    }

    @Log("添加营销活动")
    @PostMapping("/addMerchant")
    public OperationResult addMerchantSave(@RequestBody CommissionAddMchntRequest entity)  throws RedpException {
        if (StringUtils.isBlank(entity.getMerchantList()) && StringUtils.isBlank(entity.getCircleList())) {
            log.error("商户或者商圈不能为空");
            throw new RedpException("商户或者商圈不能为空");
        }
        if (StringUtils.isBlank(entity.getMcNo())) {
            log.error("活动编码不能为空");
            throw new RedpException("活动编码不能为空");
        }
        entity.setMcType("20");
        entity.setQueryType("0");
        entity.setQueryRole("00");
        return marketService.addmchntInfos(entity);
        //return OperationResult.buildSuccessResult("进行中的活动新增商户成功");
    }


    /**
     * 详情
     * flag=viewManager  管理详情页面
     * flag=chkView      审核详情页面
     * flag=check        审核页面
     * flag=rlaView      发布详情页面
     * flag=release      发布页面
     */
    @Log("详情")
    @GetMapping("/view")
    @ResponseBody
    public Map<String, Object> viewShow(HttpServletRequest request) throws RedpException {
        Map<String, Object> map=new HashMap<>();
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        map.put("instId", user.getInstId());
        String mcNo = request.getParameter("mcNo");
        //管理页面详情、审核页面详情、审核页面、发布页面详情、发布页面
        String flag = request.getParameter("flag");
        map.put("flag", flag);
        UpmpSysParam dict = upmpSysParamService.findByPrimaryKey("supportTypeFlag",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            map.put("supportTypeFlag",dict.getPrimaryValue());
        }
        dict = upmpSysParamService.findByPrimaryKey("mchntdesFlag",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            map.put("mchntdesFlag",dict.getPrimaryValue());
        }
        dict = upmpSysParamService.findByPrimaryKey("discountRule",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            map.put("discountRule",dict.getPrimaryValue());
        }
        //802行点选营销活动“发布”按钮后该活动直接发布，无须确认是否打款这一环节
        dict = upmpSysParamService.findByPrimaryKey("skipPub",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            map.put("skipPub",dict.getPrimaryValue());
        }
        if ("viewManager".equals(flag)) {
            Map<String, Object> model = marketService.setModel(mcNo, "0", "00");
            map.putAll(model);
        } else if ("check".equals(flag) || "chkView".equals(flag)) {
            Map<String, Object> model = marketService.setModel(mcNo, "0", "01");
            map.putAll(model);
        } else if ("release".equals(flag) || "rlaView".equals(flag)|| "shutdown".equals(flag) || "pause".equals(flag) || "resume".equals(flag) ) {
            Map<String, Object> model = marketService.setModel(mcNo, "0", "02");
            map.putAll(model);
        } else {
            log.info("CommissionMarketManagerController:viewShow");
        }
//        List<McMchntInfoBean> circleList = customerMarketService.getMchntCircleList(mcNo, "-1", "-1");
//        map.put("circleList", circleList);
        map.put("mcNo", mcNo);
        return map;
    }

    @Log("查询商户列表")
    @GetMapping("/mchntList")
    @ResponseBody
    public IPage<MchntQuotaInfoBean> mchntList(QueryRequest pageable, QueryMchntFeeTxnAmtLimitRequest reqDto, HttpServletRequest request) throws RedpException{
        String mchntNo = request.getParameter("mchntNo");
        String mchntName = request.getParameter("mchntName");
        reqDto.setQueryType("0");
        reqDto.setQueryRole("00");
        reqDto.setMchntNo(mchntNo);
        reqDto.setMchntName(mchntName);
        IPage<MchntQuotaInfoBean> mchntPage = marketService.findMchntPage(reqDto, pageable);
        return mchntPage;
    }

//    @Log("跳转优惠额度变更")
//    @GetMapping("/changeView")
//    public void changeView(Model model,HttpServletRequest request) {
//        String mchntNo = request.getParameter("mchntNo");
//        String mchntName = request.getParameter("mchntName");
//        String mcNo = request.getParameter("mcNo");
//
//        model.addAttribute("mchntNo", mchntNo);
//        model.addAttribute("mchntName", mchntName);
//        model.addAttribute("mcNo", mcNo);
//    }

    @Log("变更商户优惠上限")
    @PostMapping("/changeAmtLimit")
    public OperationResult changeAmtLimit(EditMchntFeeTxnAmtLimitRequest reqDto, HttpServletRequest request) throws RedpException {
        String msg = "变更成功";
        //商户号
        String mchntNo = request.getParameter("mchntNo");
        //商户参与营销活动编号
        String mcNo = request.getParameter("mcNo");
        //变更后额度
        String mchntFeeTxnAmtLimit = request.getParameter("mchntFeeTxnAmtLimit");
        //优惠额度截止日期
        String txnAmtLimitEndDate = request.getParameter("txnAmtLimitEndDate");
        //格式化日期
        if(!"".equals(txnAmtLimitEndDate)){
            txnAmtLimitEndDate = txnAmtLimitEndDate.replace("-","");
        }

        reqDto.setQueryType("0");
        reqDto.setQueryRole("00");
        reqDto.setMchntNo(mchntNo);
        reqDto.setMcNo(mcNo);
        reqDto.setMchntFeeTxnAmtLimit(mchntFeeTxnAmtLimit);
        reqDto.setTxnAmtLimitEndDate(txnAmtLimitEndDate);

        marketService.changeAmtLimit(reqDto);
        return OperationResult.buildSuccessResult(msg);
    }

    //查询商户手续费优惠额度列表
    @Log("查询商户手续费优惠额度列表")
    @GetMapping("/mchntLimitList")
    public IPage<MchntFeeDiscountInfoBean> mchntLimitList(QueryRequest pageable,QueryMchntFeeDiscountLimitRequest reqDto, HttpServletRequest request) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String mchntNo = request.getParameter("mchntNo");
        String mchntName = request.getParameter("mchntName");
        String queryOrgId = request.getParameter("signInstIdLimit");
        if((mchntNo==null||"".equals(mchntNo)) && (mchntName==null||"".equals(mchntName))){
            Result<QueryMchntFeeDiscountLimitResponse> res = new Result<>();
            return null;
        }else{
            if("".equals(queryOrgId) || queryOrgId==null){
                queryOrgId=iUpmpOrganizationService.getHeadOrgByCode(user.getInstId()).getOrgCode();
            }
            reqDto.setQueryType("0");
            reqDto.setQueryRole("00");
            reqDto.setMchntNo(mchntNo);
            reqDto.setMchntName(mchntName);
            reqDto.setQueryOrgId(queryOrgId);
            return marketService.findMchntLimitListPage(reqDto, pageable);
        }

    }
}
